﻿using Chloe.SqlServer;
using EasyNetQ;
using Mrc.Entity;
using Mrc.Entity.RabbitMqEntity;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //string conStr ="Data Source =192.168.1.228;Initial Catalog =IISLogAnalisys;Persist Security Info=True;User ID=sa;Password=123";
            //Console.WriteLine("Create conecttion factory!");
            //var factory = new ConnectionFactory()
            //{
            //    HostName = "42.51.42.120",
            //    Port = 5672,
            //    UserName = "xman",
            //    Password = "xman01111"
            //};
            ////fanout消息会广播到指定交换器的所有队列
            //var Xname = "fanout_test1";

            //Console.WriteLine("Create connection!");
            //var connection = factory.CreateConnection();//创建连接
            //Console.WriteLine("Create channel!");
            //var channel = connection.CreateModel();//创建信道
            //channel.ExchangeDeclare(exchange: Xname, type: "fanout",durable:true,autoDelete: false, arguments:null);//绑定交换器

            //Console.WriteLine("Create queue!");
            //var queueName = channel.QueueDeclare().QueueName;//生成随机名称队列
            //Console.WriteLine($"Bind {queueName} queue!");
            //channel.QueueBind(queue: queueName, exchange: Xname, routingKey: "");//当前信道绑定到随机生成的队列
            //Console.WriteLine("Start server succeed!");
            //var consumer = new EventingBasicConsumer(channel);
            //consumer.Received += (model, ea) =>
            //{
            //    var body = ea.Body;
            //    var message = Encoding.UTF8.GetString(body);
            //    //新建任务写入数据库（或自定义业务逻辑）
            //    Task.Run(() =>
            //    {
            //        using (MsSqlContext dbContext = new MsSqlContext(conStr))
            //        {
            //            dbContext.Insert<RabbitMQMessage>(new RabbitMQMessage { Body = message });
            //            using (var channel2 = connection.CreateModel()) channel2.BasicPublish(exchange: "amq.topic", routingKey: "mq", basicProperties: null, body: body);
            //        }
            //        Console.WriteLine($"receive message:\n{message}\n\n");
            //    });
            //};
            //channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);
            //Console.WriteLine(" Press enter any key to start.");
            //Console.ReadLine();
            using (var bus = RabbitHutch.CreateBus("host=42.51.42.120;port=5672;virtualHost=EasyNetQ; username=xman;password=xman01111"))
            {
                bus.Subscribe<EasyNetQTestMessage>("xdfasdf",msg => Console.WriteLine(msg.Msg));
                Console.ReadLine();
            }
            Console.ReadLine();
        }
    }
}
